package com.xbongbong.paas.controller.mobile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.credit.pojo.dto.CreditFixedApplyLimitDTO;
import com.xbongbong.pro.credit.pojo.vo.CreditFixedApplyLimitVO;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.service.CreditFixedLimitService;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * 固定额度
 * @author xingxing.xiao
 * @date 2021/01/07 11:26
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/mobile/credit/fixed")
public class MobileCreditFixedController {

    @Resource
    private CreditFixedLimitService creditFixedLimitService;

    /**
     * 查询最新的固定额度
     * @param creditFixedApplyLimitDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/latest/applyLimit", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getLatestApplyLimit(@RequestBody @Valid CreditFixedApplyLimitDTO creditFixedApplyLimitDTO, BindingResult br) {
        XbbResponse<CreditFixedApplyLimitVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try{
                CreditFixedApplyLimitVO creditFixedApplyLimitVO = creditFixedLimitService.getLatestFixedLimit(creditFixedApplyLimitDTO);
                response = new XbbResponse<>(creditFixedApplyLimitVO);
            }catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

}
